﻿Imports MySql.Data.MySqlClient

Public Module Database

    Private Const MYSQL_USER As String = "14vfu-t01"
    Private Const MYSQL_PASS As String = "gruppe01"
    Private Const MYSQL_SERVER As String = "mysql.stud.aitel.hist.no"
    Private Const MYSQL_DB As String = "14vfu-t01"

    Private tilkobling As MySqlConnection

    ' Kobler til databasen. Brukes kun internt i Database-modulen.
    Private Sub connect()

        Try
            tilkobling = New MySqlConnection("server=" & MYSQL_SERVER & ";Database=" & MYSQL_DB & ";Uid=" & MYSQL_USER & ";Pwd=" & MYSQL_PASS)
        Catch ex As Exception
            Throw ex
        End Try

    End Sub

    ' Kobler fra databasen. Brukes kun internt i Database-modulen.
    Private Sub Disconnect()
        Try
            tilkobling.Close()
            tilkobling.Dispose()
        Catch ex As Exception
            Throw ex
        End Try

    End Sub

    ' Tar imot en SQL-spørring (tekststreng), og returnerer resultat som DataTable.
    ' Eventuelle feil håndteres vha. MsgBox-meldinger.
    Public Function Query(sql As String) As DataTable

        Dim resultat As New DataTable
        Dim da As New MySqlDataAdapter

        Try

            Database.connect()

            da.SelectCommand = New MySqlCommand(sql, tilkobling)
            da.Fill(resultat)

            Database.Disconnect()
        Catch ex As Exception

            Dim feilmelding As String = ""
            Dim st As New StackTrace(True)
            Dim sf = st.GetFrame(1)

            feilmelding &= "Feil under database-spørring."
            feilmelding &= vbCrLf
            feilmelding &= vbCrLf
            feilmelding &= "Spørring: " & sql
            feilmelding &= vbCrLf
            feilmelding &= vbCrLf
            feilmelding &= "Feilmelding: " & ex.Message
            feilmelding &= vbCrLf
            feilmelding &= vbCrLf
            feilmelding &= "Funksjon: " & sf.GetMethod().ToString()
            feilmelding &= vbCrLf
            feilmelding &= "Fil: " & sf.GetMethod().DeclaringType.ToString()
            feilmelding &= vbCrLf
            feilmelding &= "Linje: " & sf.GetFileLineNumber().ToString()

            MsgBox(feilmelding, MsgBoxStyle.Critical)
        End Try
        Return resultat

    End Function

    ' Kjører spørringen, og pakker resultatet inn i resultat-parameteren.
    Public Sub Query(sql As String, ByRef resultat As DataGridView)
        resultat.DataSource = Database.Query(sql)
    End Sub

End Module
